package eu.webhib.frmwrk.servlet;

import eu.webhib.frmwrk.persistence.PersistenceMngr;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;


/*
 * see http://community.jboss.org/wiki/UsingHibernatewithTomcat
 * and http://javanotepad.blogspot.com/2007/08/managing-jpa-entitymanager-lifecycle.html
 */
public class WebContextListener implements ServletContextListener, ServletRequestListener {

   private static final Logger log = Logger.getLogger(WebContextListener.class);
   private long timeMillis;

   /** The web application initialisation process is starting. */
   @Override
   public void contextInitialized(ServletContextEvent event) {
      log.info("contextInitialized");
   }

   /** The web application is about to shut down. `*/
   @Override
   public void contextDestroyed(ServletContextEvent event) {
      log.info("contextDestroyed");
      /** Free all resources */
      PersistenceMngr.closeEntityManagerFactory();
   }

   /** The request is about to come into scope of the web application. */
   @Override
   public void requestInitialized(ServletRequestEvent sre) {
      String path = ((HttpServletRequest) sre.getServletRequest()).getServletPath();
      if (!path.startsWith("/javax.faces.resource") && !path.startsWith("/resources")) {
         log.info("------------- " + path);
         timeMillis = System.currentTimeMillis();
      }
   }

   /** The request is about to go out of scope of the web application. */
   @Override
   public void requestDestroyed(ServletRequestEvent sre) {

      String path = ((HttpServletRequest) sre.getServletRequest()).getServletPath();
      if (!path.startsWith("/javax.faces.resource") && !path.startsWith("/resources")) {
         /** close if entity manager exists and rollback transaction if one is active */
         PersistenceMngr.closeEntityManager();
         log.info("------------- " + path + "  " + (System.currentTimeMillis()
                 - timeMillis) + " ms -----------------");
      }
   }
}
